package special.graph;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Solution802 {
    public List<Integer> eventualSafeNodes(int[][] graph) {
        int n = graph.length;
        int[] out = new int[n];
        LinkedList<Integer> queue = new LinkedList<>();
        List<List<Integer>> list = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            list.add(new ArrayList<>());
        }
        for (int i = 0; i < n; i++) {
            out[i] += graph[i].length;
            for (int j = 0; j < graph[i].length; j++) {
                list.get(graph[i][j]).add(i);
            }
        }
        for (int i = 0; i < n; i++) {
            if (out[i] == 0) queue.add(i);
        }
        List<Integer> res = new ArrayList<>();
        while (!queue.isEmpty()) {
            int cur = queue.removeFirst();
            res.add(cur);
            for (int i = 0; i < list.get(cur).size(); i++) {
                out[list.get(cur).get(i)]--;
                if (out[list.get(cur).get(i)] == 0) queue.add(list.get(cur).get(cur));
            }
        }
        Collections.sort(res);
        return res;
    }
}
